//
//  Photo+Ex.swift
//  App
//
//  Created by LXF on 2018/9/21.
//  Copyright © 2018年 LXF. All rights reserved.
//

import Foundation
import FastComponent


extension UIImage {
    
    @objc public class func xx_iconfont(name: String, text: String, size: CGFloat, color: UIColor) -> UIImage {
        let size = size
        let scale = UIScreen.main.scale
        let realSize = size * scale
        let font = UIFont.xx_iconFont(name: name,size: realSize)
        UIGraphicsBeginImageContext(CGSize(width: realSize, height: realSize))
        let textStr = text as NSString
        if textStr.responds(to: NSSelectorFromString("drawAtPoint:withAttributes:")) {
            textStr.draw(at: CGPoint.zero, withAttributes: [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: color])
        }
        var image: UIImage = UIImage()
        if let cgimage = UIGraphicsGetImageFromCurrentImageContext()?.cgImage {
            image = UIImage(cgImage: cgimage, scale: scale, orientation: .up)
            UIGraphicsEndImageContext()
        }
        return image
    }
    
}

import UIKit

extension UIFont {
    
    /// "iconfont"
    @objc class public func xx_iconFont(name:String, size: CGFloat) -> UIFont {
        let font = UIFont(name: name, size: size)
        if font == nil {
            assert((font != nil), "UIFont object should not be nil, check if the font file is added to the application bundle and you're using the correct font name.")
        }
        return font ?? UIFont.systemFont(ofSize: 18)
    }
    
    
    public static func xx_registerIconFont(bundleName:String,filename:String)->Bool{
        let bundle = Bundle.subBundle(name: bundleName)
        let path = bundle.appendingPathComponent(filename + ".ttf").path
        if let data = NSData.init(contentsOfFile:path){
            return UIFont.xx_registerIconFont(fontData: data)
        }
        return false;
    }
    
    public static func xx_registerIconFont(fontData:NSData)->Bool{
        
        let fontBytes = fontData.bytes.assumingMemoryBound(to: UInt8.self)
        guard let fontDataPtr = CFDataCreate(kCFAllocatorDefault, fontBytes, fontData.length),
              let provider = CGDataProvider.init(data: fontDataPtr),
              let font = CGFont.init(provider) else {
            return false;
        }
        
        _ = UIFont.familyNames
        
        var error: Unmanaged<CFError>?
        if !CTFontManagerRegisterGraphicsFont(font, &error) {
            // let errorDescription = CFErrorCopyDescription(error as! CFError)
            print("Register Error")
            return false;
        }
        else {
            print("Register Success \(font.fullName)")
            return true;
        }
        
    }
}
